package logic

import (
	"context"
	"good_rpc/internal/svc"
	"good_rpc/pb/good"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetGoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGoodListLogic {
	return &GetGoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetGoodListLogic) GetGoodList(in *good.ListRequest) (*good.ListResponse, error) {
	goods, total, pages, err := l.svcCtx.GoodModel.FindListByPage(l.ctx, in.Page, in.PageSize)
	if err != nil {
		l.Logger.Errorf("GetGoodList failed: page=%d, page_size=%d, error: %v", in.Page, in.PageSize, err)
		return nil, err
	}

	if len(goods) == 0 {
		return &good.ListResponse{Total: total, Pages: pages, Data: []*good.GoodInfo{}}, nil
	}

	var goodsList []*good.GoodInfo
	for _, g := range goods {
		goodsList = append(goodsList, &good.GoodInfo{Id: g.Id, Name: g.Name, Stock: g.Stock, Price: g.Price})
	}
	return &good.ListResponse{Total: total, Pages: pages, Data: goodsList}, nil
}
